package impl

import (
	"github.com/RaymondCode/simple-demo/entity/po"
	"github.com/RaymondCode/simple-demo/repository"
	"gorm.io/gorm"
	"sync"
)

type Message struct {
}

func (m Message) Insert(message *po.Message, tx *gorm.DB, isTx bool) error {
	var db1 *gorm.DB
	if isTx {
		db1 = tx
	} else {
		db1 = db
	}
	return db1.Model(po.Message{}).Omit("id").Create(message).Error
}

func (m Message) QueryByCondition(message *po.Message, tx *gorm.DB, isTx bool) (*[]po.Message, error) {
	var db1 *gorm.DB
	var messages []po.Message
	if isTx {
		db1 = tx
	} else {
		db1 = db
	}
	db1.Model(po.Message{})
	if message.UserId != 0 {
		db1 = db1.Where("user_id = ?", message.UserId)
	}
	if message.ToUserId != 0 {
		db1 = db1.Where("to_user_id = ?", message.ToUserId)
	}
	return &messages, db1.Find(&messages).Error
}

var (
	message     repository.Message
	messageOnce sync.Once
)

// NewMessageDaoInstance 获取单例DAO对象
func NewMessageDaoInstance() repository.Message {
	messageOnce.Do(func() {
		message = Message{}
	})
	return message
}
